﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Telerik.WinControls;
using System.IO;
using Telerik.WinControls.UI;
using Telerik.WinControls.Data;
using Telerik.WinControls.Enumerations;
using log4net;
using System.Collections;
using System.Text.RegularExpressions;

namespace QuanLyNhaSach
{
    public partial class frmPhieuDatHang : Form
    {
        //Tao Parttern Seleton
        static frmPhieuDatHang doituong = null;
        public static frmPhieuDatHang TaoDoiTuong()
        {
            if (doituong == null)
                doituong = new frmPhieuDatHang();
            return doituong;
        }
        private void TextBoxKeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }
        public frmPhieuDatHang()
        {
            InitializeComponent();
        }

        #region "Khai báo thông tin biến"
        sv_QuanLyNhaSach.AdapterClient xuly = new sv_QuanLyNhaSach.AdapterClient();
        private ILog logger;
        public bool them { get; set; }
        ArrayList test_DSKho;
        ArrayList test_DSKH;

        int vitri;        

        double tongtien = 0;
        double tongtienhang = 0;
        double tienTamUng = 0;
        double tienthue = 0;
        double tienConLai = 0;
        string khuyenmai;
        float mucThue;
        string mahang;
        string tenhang;
        string dongia;
        string soluong;
        string thanhtien;
        string dvt;
        public string manv = frmDangNhap.maNV_FromDangNhap;
        #endregion

        #region "Ham chuyen so thanh chu"
        private static string Chu(string gNumber)
        {
            string result = "";
            switch (gNumber)
            {
                case "0":
                    result = "không";
                    break;
                case "1":
                    result = "một";
                    break;
                case "2":
                    result = "hai";
                    break;
                case "3":
                    result = "ba";
                    break;
                case "4":
                    result = "bốn";
                    break;
                case "5":
                    result = "năm";
                    break;
                case "6":
                    result = "sáu";
                    break;
                case "7":
                    result = "bảy";
                    break;
                case "8":
                    result = "tám";
                    break;
                case "9":
                    result = "chín";
                    break;
            }
            return result;
        }
        private static string Donvi(string so)
        {
            string Kdonvi = "";

            if (so.Equals("1"))
                Kdonvi = "";
            if (so.Equals("2"))
                Kdonvi = "nghìn";
            if (so.Equals("3"))
                Kdonvi = "triệu";
            if (so.Equals("4"))
                Kdonvi = "tỷ";
            if (so.Equals("5"))
                Kdonvi = "nghìn tỷ";
            if (so.Equals("6"))
                Kdonvi = "triệu tỷ";
            if (so.Equals("7"))
                Kdonvi = "tỷ tỷ";

            return Kdonvi;
        }
        private static string Tach(string tach3)
        {
            string Ktach = "";
            if (tach3.Equals("000"))
                return "";
            if (tach3.Length == 3)
            {
                string tr = tach3.Trim().Substring(0, 1).ToString().Trim();
                string ch = tach3.Trim().Substring(1, 1).ToString().Trim();
                string dv = tach3.Trim().Substring(2, 1).ToString().Trim();
                if (tr.Equals("0") && ch.Equals("0"))
                    Ktach = " không trăm lẻ " + Chu(dv.ToString().Trim()) + " ";
                if (!tr.Equals("0") && ch.Equals("0") && dv.Equals("0"))
                    Ktach = Chu(tr.ToString().Trim()).Trim() + " trăm ";
                if (!tr.Equals("0") && ch.Equals("0") && !dv.Equals("0"))
                    Ktach = Chu(tr.ToString().Trim()).Trim() + " trăm lẻ " + Chu(dv.Trim()).Trim() + " ";
                if (tr.Equals("0") && Convert.ToInt32(ch) > 1 && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                    Ktach = " không trăm " + Chu(ch.Trim()).Trim() + " mươi " + Chu(dv.Trim()).Trim() + " ";
                if (tr.Equals("0") && Convert.ToInt32(ch) > 1 && dv.Equals("0"))
                    Ktach = " không trăm " + Chu(ch.Trim()).Trim() + " mươi ";
                if (tr.Equals("0") && Convert.ToInt32(ch) > 1 && dv.Equals("5"))
                    Ktach = " không trăm " + Chu(ch.Trim()).Trim() + " mươi lăm ";
                if (tr.Equals("0") && ch.Equals("1") && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                    Ktach = " không trăm mười " + Chu(dv.Trim()).Trim() + " ";
                if (tr.Equals("0") && ch.Equals("1") && dv.Equals("0"))
                    Ktach = " không trăm mười ";
                if (tr.Equals("0") && ch.Equals("1") && dv.Equals("5"))
                    Ktach = " không trăm mười lăm ";
                if (Convert.ToInt32(tr) > 0 && Convert.ToInt32(ch) > 1 && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm " + Chu(ch.Trim()).Trim() + " mươi " + Chu(dv.Trim()).Trim() + " ";
                if (Convert.ToInt32(tr) > 0 && Convert.ToInt32(ch) > 1 && dv.Equals("0"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm " + Chu(ch.Trim()).Trim() + " mươi ";
                if (Convert.ToInt32(tr) > 0 && Convert.ToInt32(ch) > 1 && dv.Equals("5"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm " + Chu(ch.Trim()).Trim() + " mươi lăm ";
                if (Convert.ToInt32(tr) > 0 && ch.Equals("1") && Convert.ToInt32(dv) > 0 && !dv.Equals("5"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm mười " + Chu(dv.Trim()).Trim() + " ";

                if (Convert.ToInt32(tr) > 0 && ch.Equals("1") && dv.Equals("0"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm mười ";
                if (Convert.ToInt32(tr) > 0 && ch.Equals("1") && dv.Equals("5"))
                    Ktach = Chu(tr.Trim()).Trim() + " trăm mười lăm ";

            }


            return Ktach;

        }
        public static string So_chu(double gNum)
        {
            if (gNum == 0)
                return "Không đồng";

            string lso_chu = "";
            string tach_mod = "";
            string tach_conlai = "";
            double Num = Math.Round(gNum, 0);
            string gN = Convert.ToString(Num);
            int m = Convert.ToInt32(gN.Length / 3);
            int mod = gN.Length - m * 3;
            string dau = "[+]";

            // Dau [+ , - ]
            if (gNum < 0)
                dau = "[-]";
            dau = "";

            // Tach hang lon nhat
            if (mod.Equals(1))
                tach_mod = "00" + Convert.ToString(Num.ToString().Trim().Substring(0, 1)).Trim();
            if (mod.Equals(2))
                tach_mod = "0" + Convert.ToString(Num.ToString().Trim().Substring(0, 2)).Trim();
            if (mod.Equals(0))
                tach_mod = "000";
            // Tach hang con lai sau mod :
            if (Num.ToString().Length > 2)
                tach_conlai = Convert.ToString(Num.ToString().Trim().Substring(mod, Num.ToString().Length - mod)).Trim();

            ///don vi hang mod 
            int im = m + 1;
            if (mod > 0)
                lso_chu = Tach(tach_mod).ToString().Trim() + " " + Donvi(im.ToString().Trim());
            /// Tach 3 trong tach_conlai

            int i = m;
            int _m = m;
            int j = 1;
            string tach3 = "";
            string tach3_ = "";

            while (i > 0)
            {
                tach3 = tach_conlai.Trim().Substring(0, 3).Trim();
                tach3_ = tach3;
                lso_chu = lso_chu.Trim() + " " + Tach(tach3.Trim()).Trim();
                m = _m + 1 - j;
                if (!tach3_.Equals("000"))
                    lso_chu = lso_chu.Trim() + " " + Donvi(m.ToString().Trim()).Trim();
                tach_conlai = tach_conlai.Trim().Substring(3, tach_conlai.Trim().Length - 3);

                i = i - 1;
                j = j + 1;
            }
            if (lso_chu.Trim().Substring(0, 1).Equals("k"))
                lso_chu = lso_chu.Trim().Substring(10, lso_chu.Trim().Length - 10).Trim();
            if (lso_chu.Trim().Substring(0, 1).Equals("l"))
                lso_chu = lso_chu.Trim().Substring(2, lso_chu.Trim().Length - 2).Trim();
            if (lso_chu.Trim().Length > 0)
                lso_chu = dau.Trim() + " " + lso_chu.Trim().Substring(0, 1).Trim().ToUpper() + lso_chu.Trim().Substring(1, lso_chu.Trim().Length - 1).Trim() + " đồng chẵn.";

            return lso_chu.ToString().Trim();

        }
        #endregion
        private bool ktmh(string mamh)
        {
            DataSet ds = new DataSet();
            ds.ReadXml(new StringReader(xuly.selectqueryByText("select mamh from mathang where mamh like'" + mamh.Trim() + "'")));
            if (ds.Tables.Count > 0)
            {
                return true;
            }
            return false;
        }
        private void frmPhieuDatHang_Load(object sender, EventArgs e)
        {
            //Enter
            this.KeyDown += new KeyEventHandler(frmPhieuDatHang_KeyDown);
            txt_chungtu.KeyDown += new KeyEventHandler(txt_chungtu_KeyDown);
            mcb_khohang.KeyDown += new KeyEventHandler(mcb_khohang_KeyDown);
            mcb_khachhang.KeyDown += new KeyEventHandler(mcb_khachhang_KeyDown);
            mcb_tenmathang.KeyDown += new KeyEventHandler(mcb_tenmathang_KeyDown);
            txt_dongia.KeyDown += new KeyEventHandler(txt_soluong_KeyDown);
            txt_khuyenmai.KeyDown += new KeyEventHandler(txt_soluong_KeyDown);
            txt_soluong.KeyDown += new KeyEventHandler(txt_soluong_KeyDown);
            bt_chuyenxuong.KeyDown += new KeyEventHandler(bt_chuyenxuong_KeyDown);
            txt_tamung.KeyDown += new KeyEventHandler(txt_tamung_KeyDown);
            txt_mucthue.KeyDown += new KeyEventHandler(txt_tamung_KeyDown);
            bt_luu.KeyDown += new KeyEventHandler(bt_luu_KeyDown);
            //-------------

            logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            try
            {
                //set ngay thang hien tai
                dtp_ngaydat.Value = DateTime.Now;
                dtp_ngayhengiao.Value = DateTime.Now;
                //focus vao so chung tu
                txt_chungtu.Focus();
                //Lay Ten Nhan Vien
                DataSet ds_TenNhanVien = new DataSet();
                ds_TenNhanVien.ReadXml(new StringReader(xuly.selectqueryByText("select HoTenNV from NhanVien where MaNV = '" + frmDangNhap.maNV_FromDangNhap + "'")));
                if (ds_TenNhanVien.Tables.Count > 0)
                    txt_TenNhanVien.Text = ds_TenNhanVien.Tables[0].Rows[0][0].ToString();

                //Load DS Nha Khach Hang
                Load_DanhSach_KhachHang();

                //Load DS Kho
                Load_DanhSach_KhoHang();

                //Load DS Mat Hang
                Load_DanhSach_MatHang();
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }

        }

        void frmPhieuDatHang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.F2)
            {
                txt_tamung.Focus();
                txt_tamung.Text = "";
                txt_tamung.SelectionStart = txt_tamung.Text.Length;
                
            }
            if (e.KeyData == Keys.F3)
            {
                Luu();
            }
        }

        void bt_luu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                Luu();
            }
        }

        void txt_tamung_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                bt_luu.Focus();
            }
        }

        void bt_chuyenxuong_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                bt_chuyenxuong.Click+=new EventHandler(bt_chuyenxuong_Click);
                mcb_tenmathang.Focus();
            }
        }

        void txt_soluong_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                bt_chuyenxuong.Focus();
            }
        }

        void mcb_tenmathang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                txt_soluong.Focus();
                txt_soluong.SelectionStart = txt_soluong.Text.Length;
            }
        }

        void mcb_khachhang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                mcb_tenmathang.Focus();
            }
        }

        void mcb_khohang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                mcb_khachhang.Focus();
        }

        void txt_chungtu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                mcb_khohang.Focus();
        }

        private void Load_DanhSach_MatHang()
        {
            try
            {
                //Chinh do dai cua cac cot trong muiltcombobox
                RadMultiColumnComboBoxElement multiColumnComboElement = this.mcb_tenmathang.MultiColumnComboBoxElement;
                multiColumnComboElement.DropDownSizingMode = SizingMode.UpDownAndRightBottom;
                multiColumnComboElement.DropDownMinSize = new Size(600, 200);

                DataSet ds_MatHang = new DataSet();
                ds_MatHang.ReadXml(new StringReader(xuly.LayDS_MatHang()));
                if (ds_MatHang.Tables.Count > 0)
                {
                    mcb_tenmathang.DataSource = ds_MatHang.Tables[0];
                    mcb_tenmathang.DisplayMember = "TenMH";
                    mcb_tenmathang.ValueMember = "MaMH";
                    mcb_tenmathang.SelectedIndex = -1;
                    //mcb_tenmathang.Text = "[Chọn mặt hàng]";
                }
                FilterDescriptor des_mh = new FilterDescriptor(this.mcb_tenmathang.DisplayMember, FilterOperator.StartsWith, string.Empty);
                mcb_tenmathang.EditorControl.FilterDescriptors.Add(des_mh);
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }

        }

        private void Load_DanhSach_KhoHang()
        {
            try
            {
                //Chinh do dai cua cac cot trong muiltcombobox
                RadMultiColumnComboBoxElement multiColumnComboElement = this.mcb_khohang.MultiColumnComboBoxElement;
                multiColumnComboElement.DropDownSizingMode = SizingMode.UpDownAndRightBottom;
                multiColumnComboElement.DropDownMinSize = new Size(300, 200);

                DataSet ds_Kho = new DataSet();
                ds_Kho.ReadXml(new StringReader(xuly.LayDS_Kho()));
                if (ds_Kho.Tables.Count > 0)
                {
                    test_DSKho = new ArrayList();
                    for (int i = 0; i < ds_Kho.Tables[0].Rows.Count; i++)
                    {
                        test_DSKho.Add(ds_Kho.Tables[0].Rows[i]["TenKho"].ToString().Trim());
                    }

                    mcb_khohang.DataSource = ds_Kho.Tables[0];
                    mcb_khohang.DisplayMember = "TenKho";
                    mcb_khohang.ValueMember = "MaKho";
                    mcb_khohang.SelectedIndex = -1;
                    //mcb_khohang.Text = "[Chọn kho]";
                }
                FilterDescriptor des_kho = new FilterDescriptor(this.mcb_khohang.ValueMember, FilterOperator.StartsWith, string.Empty);
                mcb_khohang.EditorControl.FilterDescriptors.Add(des_kho);
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }

        }

        private void Load_DanhSach_KhachHang()
        {
            try
            {
                //Chinh do dai cua cac cot trong muiltcombobox
                RadMultiColumnComboBoxElement multiColumnComboElement = this.mcb_khachhang.MultiColumnComboBoxElement;
                multiColumnComboElement.DropDownSizingMode = SizingMode.UpDownAndRightBottom;
                multiColumnComboElement.DropDownMinSize = new Size(500, 200);

                DataSet ds_KhachHang = new DataSet();
                ds_KhachHang.ReadXml(new StringReader(xuly.LayDS_KhachHang()));
                if (ds_KhachHang.Tables.Count > 0)
                {
                    test_DSKH = new ArrayList();
                    for (int i = 0; i < ds_KhachHang.Tables[0].Rows.Count; i++)
                    {
                        test_DSKH.Add(ds_KhachHang.Tables[0].Rows[i]["HoTenKH"].ToString().Trim());
                    }

                    mcb_khachhang.DataSource = ds_KhachHang.Tables[0];
                    mcb_khachhang.DisplayMember = "HoTenKH";
                    mcb_khachhang.ValueMember = "MaKH";
                    mcb_khachhang.SelectedIndex = -1;
                    //mcb_khachhang.Text = "[Chọn khách hàng]";
                }
                FilterDescriptor des_kh = new FilterDescriptor(this.mcb_khachhang.DisplayMember, FilterOperator.StartsWith, string.Empty);
                mcb_khachhang.EditorControl.FilterDescriptors.Add(des_kh);
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }

        }

        private void mcb_khachhang_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (mcb_khachhang.Text == "")
                {
                    txt_diachi.Text = "";
                }
                else
                {
                    txt_diachi.Text = mcb_khachhang.EditorControl.Rows[mcb_khachhang.SelectedIndex].Cells["DiaChiKH"].Value.ToString().Trim();
                    //DataSet ds_DiaChi = new DataSet();
                    //ds_DiaChi.ReadXml(new StringReader(xuly.selectqueryByText("select DiaChiKH from KhachHang where MaKH = '" + mcb_khachhang.SelectedValue.ToString() + "' ")));
                    //if (ds_DiaChi.Tables.Count > 0)
                    //{
                    //    if (mcb_khachhang.SelectedIndex != -1)
                    //    {
                    //        txt_diachi.Text = ds_DiaChi.Tables[0].Rows[0][0].ToString();
                    //    }
                    //}
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }

        }

        private void mcb_tenmathang_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (mcb_tenmathang.Text == "")
                {
                    txt_mamh.Text = "";
                    txt_dongia.Text = "0";
                    txt_soluong.Text = "1";
                    txt_thanhtien.Text = "0";
                    ddl_dvt.Text = "";
                    txt_khuyenmai.Text = "0";
                }
                else
                {
                    txt_mamh.Text = mcb_tenmathang.SelectedValue.ToString().Trim();
                    txt_dongia.Text = double.Parse(mcb_tenmathang.EditorControl.Rows[mcb_tenmathang.SelectedIndex].Cells["DonGiaSi"].Value.ToString()).ToString("#,##0");
                    ddl_dvt.Text = mcb_tenmathang.EditorControl.Rows[mcb_tenmathang.SelectedIndex].Cells["DVT"].Value.ToString().Trim();
                    txt_khuyenmai.Text = mcb_tenmathang.EditorControl.Rows[mcb_tenmathang.SelectedIndex].Cells["KhuyenMai"].Value.ToString().Trim();

                    //DataSet ds_ThongTinSachDaChon = new DataSet();
                    //ds_ThongTinSachDaChon.ReadXml(new StringReader(xuly.selectqueryByText("select MaMH,DonGiaNhap,DVT,KhuyenMai from MatHang where MaMH = '" + mcb_tenmathang.SelectedValue.ToString() + "' ")));
                    //if (ds_ThongTinSachDaChon.Tables.Count > 0)
                    //{
                    //    double dongiaMatHang = double.Parse(ds_ThongTinSachDaChon.Tables[0].Rows[0][1].ToString());
                    //    if (mcb_tenmathang.SelectedIndex != -1)
                    //    {
                    //        txt_mamh.Text = ds_ThongTinSachDaChon.Tables[0].Rows[0][0].ToString();
                    //        txt_dongia.Text = dongiaMatHang.ToString("#,##0");
                    //        ddl_dvt.Text = ds_ThongTinSachDaChon.Tables[0].Rows[0][2].ToString();
                    //        txt_khuyenmai.Text = ds_ThongTinSachDaChon.Tables[0].Rows[0][3].ToString();
                    //    }
                    //}
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }       

        private void txt_soluong_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txt_soluong.Text.Length != 0)
                {
                    txt_soluong.Text = double.Parse(txt_soluong.Text).ToString("#,##0");
                    double thanhtien = double.Parse(txt_soluong.Text) * double.Parse(txt_dongia.Text) - double.Parse(txt_soluong.Text) * double.Parse(txt_dongia.Text) * float.Parse(txt_khuyenmai.Text) / 100;
                    txt_thanhtien.Text = thanhtien.ToString("#,##0");
                }
                //Tra con trỏ về cuối dòng
                txt_soluong.SelectionStart = txt_soluong.Text.Length;
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }

        }

        private void txt_dongia_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txt_dongia.Text.Length != 0)
                {
                    txt_dongia.Text = double.Parse(txt_dongia.Text).ToString("#,##0");
                    double thanhtien = double.Parse(txt_soluong.Text) * double.Parse(txt_dongia.Text) - double.Parse(txt_soluong.Text) * double.Parse(txt_dongia.Text) * float.Parse(txt_khuyenmai.Text) / 100;
                    txt_thanhtien.Text = thanhtien.ToString("#,##0");
                }
                //cho con tro ve cuoi textbox
                txt_dongia.SelectionStart = txt_dongia.Text.Length;   
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private void txt_khuyenmai_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txt_khuyenmai.Text.Trim() != "")
                {
                    if (int.Parse(txt_khuyenmai.Text) != 0)
                    {
                        double thanhtien = double.Parse(txt_soluong.Text) * double.Parse(txt_dongia.Text) - double.Parse(txt_soluong.Text) * double.Parse(txt_dongia.Text) * float.Parse(txt_khuyenmai.Text) / 100;
                        txt_thanhtien.Text = thanhtien.ToString("#,##0");
                        txt_thanhtien.Text = (int.Parse(txt_dongia.Text) * int.Parse(txt_soluong.Text) - int.Parse(txt_dongia.Text) * int.Parse(txt_soluong.Text) * (float.Parse(txt_khuyenmai.Text) / 100)).ToString("#,##0");
                    }
                    else
                    {
                        txt_thanhtien.Text = (int.Parse(txt_dongia.Text) * int.Parse(txt_soluong.Text)).ToString("#,##0");
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private void txt_mucthue_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txt_mucthue.Text.Length != 0)
                {
                    double tienthueTam = tongtien * double.Parse(txt_mucthue.Text)/100;
                    txt_tienthue.Text = tienthueTam.ToString("#,##0");

                    txt_thanhtienhd.Text = (tongtien + tienthueTam).ToString("#,##0");
                    txt_bangchu.Text = So_chu(double.Parse(txt_thanhtienhd.Text));
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }

        }

        private void txt_tamung_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txt_tamung.Text.Length != 0)
                {
                    txt_tamung.Text = double.Parse(txt_tamung.Text).ToString("#,##0");

                    tienConLai = tongtien - double.Parse(txt_tamung.Text);
                    txt_conlai.Text = tienConLai.ToString("#,##0");

                    tienConLai = double.Parse(txt_tongtien.Text) - double.Parse(txt_tamung.Text);
                    txt_conlai.Text = tienConLai.ToString("#,##0");
                }
                //cho con tro ve cuoi textbox
                txt_tamung.SelectionStart = txt_tamung.Text.Length;
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }

        }

        private void txt_tongtien_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txt_tongtien.Text.Trim() != "0")
                    txt_thanhtienhd.Text = (double.Parse(txt_tongtien.Text) + double.Parse(txt_tienthue.Text)).ToString("#,##0");
            }
            catch (Exception) { }
        }

        private void txt_thanhtienhd_TextChanged(object sender, EventArgs e)
        {
            try
            {
                txt_bangchu.Text = So_chu(double.Parse(txt_thanhtienhd.Text));
            }
            catch (Exception) { }
        }

        private void bt_chuyenxuong_Click(object sender, EventArgs e)
        {
            errorProvider1.Clear();
            if (mcb_khohang.Text.Trim() == "")
            {
                errorProvider1.SetError(mcb_khohang, "Chưa chọn kho.");
                mcb_khohang.Focus();
                return;
            }
            if (mcb_khachhang.Text == "")
            {
                errorProvider1.SetError(mcb_khachhang, "Chưa chọn khách hàng.");
                mcb_khachhang.Focus();
                return;
            }

            if (txt_mamh.Text.Trim() == "")
            {
                errorProvider1.SetError(txt_mamh, "Chưa chọn mặt hàng");
                mcb_tenmathang.Focus();
                return;
            }
            if (ktmh(txt_mamh.Text.Trim()) == false)
            {
                errorProvider1.SetError(txt_mamh, "Mặt hàng không hợp lệ");
                mcb_tenmathang.Focus();
                return;
            }
            if (txt_soluong.Text.Trim() == "" || int.Parse(txt_soluong.Text) == 0)
            {
                errorProvider1.SetError(txt_soluong, "Số lượng không hợp lệ");
                txt_soluong.Focus();
                return;
            }
            if (txt_dongia.Text.Trim() == "" || double.Parse(txt_dongia.Text) == 0)
            {
                errorProvider1.SetError(txt_dongia, "Đơn giá không hợp lệ");
                txt_dongia.Focus();
                return;
            }
            try
            {
                if (gv_ddh.Rows.Count > 0)
                {
                    //Tang so luong va thay doi tong thanh tien + Truong hop gia tien khac nhau
                    for (int i = 0; i < gv_ddh.Rows.Count; i++)
                    {
                        if (mcb_tenmathang.SelectedValue.ToString().Trim() == gv_ddh.Rows[i].Cells["mamh"].Value.ToString().Trim() && txt_dongia.Text.Trim() == gv_ddh.Rows[i].Cells["DonGia"].Value.ToString().Trim())
                        {
                            gv_ddh.Rows[i].Cells["soluong"].Value = (int.Parse(gv_ddh.Rows[i].Cells["soluong"].Value.ToString()) + int.Parse(txt_soluong.Text.Trim())).ToString("#,##0");
                            gv_ddh.Rows[i].Cells["thanhtien"].Value = (int.Parse(gv_ddh.Rows[i].Cells["soluong"].Value.ToString()) * double.Parse(gv_ddh.Rows[i].Cells["dongia"].Value.ToString()) - int.Parse(gv_ddh.Rows[i].Cells["soluong"].Value.ToString()) * double.Parse(gv_ddh.Rows[i].Cells["dongia"].Value.ToString()) * double.Parse(gv_ddh.Rows[i].Cells["chietkhau"].Value.ToString()) / 100).ToString("#,##0");
                            //Tinh tong tien hang
                            tongtienhang = 0;
                            for (int j = 0; j < gv_ddh.Rows.Count; j++)
                            {
                                tongtienhang += double.Parse(gv_ddh.Rows[j].Cells["ThanhTien"].Value.ToString());
                            }
                            txt_tongtien.Text = tongtienhang.ToString("#,##0");
                            mcb_tenmathang.Focus();
                            return;
                        }
                    }
                }
                //Gan gia tri cho bien
                mahang = txt_mamh.Text;
                tenhang = mcb_tenmathang.Text.Trim();
                dvt = ddl_dvt.Text;
                dongia = txt_dongia.Text;
                soluong = txt_soluong.Text;
                thanhtien = txt_thanhtien.Text;
                khuyenmai = txt_khuyenmai.Text;
                //gan gia tri cho bien
                if (gv_ddh.Rows.Count != 0)
                    vitri = gv_ddh.Rows.Count;
                else
                    vitri = 0;
                //them thong tin vao gridview
                gv_ddh.Rows.AddNew();
                gv_ddh.Rows[vitri].Cells["MaMH"].Value = mahang;
                gv_ddh.Rows[vitri].Cells["TenMH"].Value = tenhang;
                gv_ddh.Rows[vitri].Cells["DVT"].Value = dvt;
                gv_ddh.Rows[vitri].Cells["KhuyenMai"].Value = khuyenmai;
                gv_ddh.Rows[vitri].Cells["DonGia"].Value = dongia;
                gv_ddh.Rows[vitri].Cells["SoLuong"].Value = soluong;
                gv_ddh.Rows[vitri].Cells["ThanhTien"].Value = thanhtien;
                //Them nut xoa trong Gridview
                if (gv_ddh.Columns.GetColumnByFieldName("xoa").Length == 0)
                {
                    GridViewCommandColumn btnColumn = new GridViewCommandColumn();
                    btnColumn.FieldName = "xoa";
                    btnColumn.Name = "xoa";
                    btnColumn.UseDefaultText = true;
                    btnColumn.DefaultText = "Xóa";
                    gv_ddh.Columns.Insert(gv_ddh.Columns.Count, btnColumn);
                }
                //Tao STT cho Girdview
                if (gv_ddh.Rows.Count > 0)
                {
                    tongtienhang = 0;
                    tongtien = 0;
                    for (int i = 0; i < gv_ddh.Rows.Count; i++)
                    {
                        gv_ddh.Rows[i].Cells["STT"].Value = i + 1;
                        //Tinh Tong Tien
                        tongtienhang += double.Parse(gv_ddh.Rows[i].Cells["ThanhTien"].Value.ToString());
                    }
                    txt_tongtien.Text = tongtienhang.ToString("#,##0");
                    tongtien = tongtienhang + double.Parse(txt_tienthue.Text);
                    txt_thanhtienhd.Text = tongtien.ToString("#,##0");
                    txt_bangchu.Text = So_chu(tongtien);
                }
                //Xoa bo thong tin trong cac o trong
                txt_mamh.Text = "";
                mcb_tenmathang.SelectedIndex = -1;
                txt_soluong.Text = "1";
                txt_dongia.Text = "0";
                ddl_dvt.Text = "";
                txt_thanhtien.Text = "0";
                txt_khuyenmai.Text = "0";
                mcb_tenmathang.Focus();

            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private void bt_luu_Click(object sender, EventArgs e)
        {
            Luu();

        }

        private void Luu()
        {
            errorProvider1.Clear();
            lbl_ThongBao.Text = "Thông báo!";
            if (txt_chungtu.Text.Trim() == "")
            {
                errorProvider1.SetError(txt_chungtu, "Vui lòng nhập thông tin chứng từ.");
                txt_chungtu.Focus();
                return;
            }
            if (mcb_khohang.Text.Trim() == "")
            {
                errorProvider1.SetError(mcb_khohang, "Chưa chọn kho hàng");
                mcb_khohang.Focus();
                return;
            }
            if (test_DSKho.Contains(mcb_khohang.Text.Trim()) == false)
            {
                errorProvider1.SetError(mcb_khohang, "Nhập sai thông tin Kho Hàng.");
                mcb_khohang.Focus();
                return;
            }
            if (mcb_khachhang.Text.Trim() == "")
            {
                errorProvider1.SetError(mcb_khachhang, "Chưa chọn NCC");
                mcb_khachhang.Focus();
                return;
            }
            if (test_DSKH.Contains(mcb_khachhang.Text.Trim()) == false)
            {
                errorProvider1.SetError(mcb_khachhang, "Nhập sai thông tin Nhà Cung Cấp");
                mcb_khachhang.Focus();
                return;
            }
            if (gv_ddh.Rows.Count == 0)
            {
                lbl_ThongBao.Text = "Chưa có dữ liệu chi tiết mua hàng";
                errorProvider1.SetError(lbl_ThongBao, "Chưa nhập chi tiết Phiếu đặt hàng");
                mcb_tenmathang.Focus();
                return;
            }
            else
            {
                #region "Kiem tra thông tin từng cell tren lưới"
                for (int i = 0; i < gv_ddh.Rows.Count; i++)
                {
                    try
                    {
                        if (Regex.IsMatch(gv_ddh.Rows[i].Cells["SoLuong"].Value.ToString().Trim(), @"^[0-9,',']{0,5}$") == false || int.Parse(gv_ddh.CurrentRow.Cells["SoLuong"].Value.ToString()) < 0)
                        {
                            lbl_ThongBao.Text = "Số lượng nhập vào phải lớn hơn không (số lượng > 0) và là con số nguyên. Vui lòng nhập lại";
                            errorProvider1.RightToLeft = false;
                            errorProvider1.SetError(lbl_ThongBao, "Xem lại thông tin trên lưới.");
                            return;
                        }
                        if (Regex.IsMatch(gv_ddh.Rows[i].Cells["DonGia"].Value.ToString(), @"^[0-9,',']{0,9}$") == false)
                        {
                            lbl_ThongBao.Text = "Đơn giá nhập vào là số nguyên không âm. Vui lòng nhập lại";
                            errorProvider1.RightToLeft = false;
                            errorProvider1.SetError(lbl_ThongBao, "Xem lại thông tin trên lưới.");
                            return;
                        }
                        if (Regex.IsMatch(gv_ddh.Rows[i].Cells["KhuyenMai"].Value.ToString().Trim(), @"^\d{1,2}$") == false || int.Parse(gv_ddh.CurrentRow.Cells["KhuyenMai"].Value.ToString()) > 50)
                        {
                            lbl_ThongBao.Text = "Số khuyến mãi từ 0 - 50 %";
                            errorProvider1.RightToLeft = false;
                            errorProvider1.SetError(lbl_ThongBao, "Xem lại thông tin trên lưới.");
                            return;
                        }
                        lbl_ThongBao.Text = "Thông báo!";
                        errorProvider1.RightToLeft = true;
                    }
                    catch (Exception ex)
                    {
                        logger.Error("Error: " + ex.Message);
                    }
                }
                #endregion
            }
            if (dtp_ngayhengiao.Value < DateTime.Now)
            {
                errorProvider1.SetError(dtp_ngayhengiao, "Ngày Hẹn phải lớn hơn hoặc bằng Ngày hiện tại.");
                dtp_ngayhengiao.Focus();
                return;
            }
            try
            {
                //Khai Bao Thong Tin Bien 
                string maKHDH = Lay_MaMoiNhat();
                string maKho = mcb_khohang.SelectedValue.ToString();
                string maKH = mcb_khachhang.SelectedValue.ToString();
                string soChungTu = txt_chungtu.Text;
                DateTime ngayThang = dtp_ngaydat.Value;
                string ghiChu = txt_ghichu.Text;
                double tongDonHang = tongtien;
                double tamung = tienTamUng;
                double conlai = tienConLai;
                string diachi = txt_diachi.Text;
                DateTime ngayBanGiao = dtp_ngayhengiao.Value;
                //Xu li them vao bang PhieuDatHangNCC
                if (!xuly.InsertPhieuKHDatHang(maKHDH, maKho, maKH, manv, soChungTu, ngayThang, diachi, ghiChu, tongDonHang, tamung, conlai, ngayBanGiao))
                {
                    MessageBox.Show("Loi Them Phieu Dat Hang");
                    return;
                }
                //Duyet qua Gridview de them vao bang Chi Tiet Dat Hang 
                for (int i = 0; i < gv_ddh.Rows.Count; i++)
                {
                    string maMH = gv_ddh.Rows[i].Cells["MaMH"].Value.ToString().Trim();
                    int soLuong = int.Parse(gv_ddh.Rows[i].Cells["SoLuong"].Value.ToString());
                    string dVT = gv_ddh.Rows[i].Cells["DVT"].Value.ToString();
                    double donGia = double.Parse(gv_ddh.Rows[i].Cells["DonGia"].Value.ToString());
                    float chietKhau = float.Parse(gv_ddh.Rows[i].Cells["KhuyenMai"].Value.ToString()) / 100;
                    double thanhTien = double.Parse(gv_ddh.Rows[i].Cells["ThanhTien"].Value.ToString());
                    bool daGiao = false;
                    //Them tung chi tiet vao CT Dat Hang 
                    if (!xuly.InsertCTKHDatHang(maMH, maKHDH, soLuong, dVT, donGia, chietKhau, thanhTien, daGiao))
                    {
                        MessageBox.Show("Lưu thất bại! Vui lòng kiểm tra lại thông tin mặt hàng hoặc gặp kỹ thuật.", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                        return;
                    }
                }
                MessageBox.Show("Hoá đơn lưu thành công.", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //Xoa het thong tin cua Phieu Dat tren nếu click phieu In sau khi luu                
                //In phieu sau khi luu da dc Kich
                if (chk_inphieu.Checked == true)
                {
                    //Dua len Report  
                    Report.frm_In_PhieuKHDatHang khdh = new Report.frm_In_PhieuKHDatHang();
                    khdh.MaKHDH = maKHDH;
                    khdh.ShowDialog();

                    //Xoa tat cac thong tin sau khi da Luu hoa don va In phieu
                    gv_ddh.Rows.Clear();
                    txt_tongtien.Text = "0";
                    txt_thanhtienhd.Text = "0";
                    txt_mucthue.Text = "0";
                    txt_tamung.Text = "0";
                    txt_conlai.Text = "0";
                    txt_tienthue.Text = "0";
                    txt_bangchu.Text = "không đồng chẳn.";
                    txt_chungtu.Focus();
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private string Lay_MaMoiNhat()
        {
            DataSet ds_tam = new DataSet();
            string mamoi="";
            try
            {
                string maTam = "DH" + DateTime.Today.Year.ToString("0000") + DateTime.Today.Month.ToString("00");
                ds_tam.ReadXml(new StringReader(xuly.selectqueryByText("select top 1 MaKHDH from PhieuKHDatHang where MaKHDH like '%" + maTam + "%'order by MaKHDH desc")));
                if (ds_tam.Tables.Count == 0)
                    mamoi = maTam + "0001";
                else
                {
                    string matam = ds_tam.Tables[0].Rows[0][0].ToString();
                    string kituso = matam.Substring(11, 4).ToString();
                    int somoi = int.Parse(kituso) + 1;
                    mamoi = maTam + somoi.ToString("0000");
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }


            return mamoi;
        }

        private void gv_ddh_CommandCellClick(object sender, EventArgs e)
        {
            double tongtien_sauxoa = 0;
            try
            {
                if (MessageBox.Show("Bạn muốn xóa thông tin mặt hàng này ?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (gv_ddh.Rows.Count == 1)
                    {
                        gv_ddh.Rows.Clear();
                    }
                    else
                    {
                        gv_ddh.Rows.RemoveAt(gv_ddh.CurrentRow.Index);
                        for (int i = 0; i < gv_ddh.Rows.Count; i++)
                        {
                            gv_ddh.Rows[i].Cells["STT"].Value = i + 1;
                        }
                    }
                    for (int j = 0; j < gv_ddh.Rows.Count; j++)
                    {
                        tongtien_sauxoa += double.Parse(gv_ddh.Rows[j].Cells["ThanhTien"].Value.ToString());
                    }
                    txt_tongtien.Text = tongtien_sauxoa.ToString("#,##0");
                    if (txt_mucthue.Text.Length != 0)
                    {
                        if (txt_tongtien.Text.Length != 0)
                        {
                            tienthue = double.Parse(txt_tongtien.Text) * double.Parse(txt_mucthue.Text) / 100;
                            txt_tienthue.Text = tienthue.ToString("#,##0");
                            txt_thanhtienhd.Text = (double.Parse(txt_tongtien.Text) + tienthue).ToString("#,##0");
                            txt_bangchu.Text = So_chu(double.Parse(txt_thanhtienhd.Text));
                        }
                    }
                    else
                    {
                        txt_tienthue.Text = "0";
                        txt_thanhtienhd.Text = txt_tongtien.Text;
                        txt_bangchu.Text = So_chu(double.Parse(txt_thanhtienhd.Text));
                    }
                }                
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private void bt_thoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //private void bt_taomoi_Click(object sender, EventArgs e)
        //{
        //    mcb_khachhang.Text = "";
        //    mcb_tenmathang.Text = "";
        //    mcb_khohang.Text = "";
        //    txt_chungtu.Text = "";
        //    txt_diachi.Text = "";
        //    txt_ghichu.Text = "";
        //    txt_mamh.Text = "";
        //    txt_soluong.Text = "1";
        //    ddl_dvt.Text = "";
        //    txt_dongia.Text = "0";
        //    txt_khuyenmai.Text = "0";
        //    txt_thanhtien.Text = "0";
        //    txt_tongtien.Text = "0";
        //    txt_thanhtienhd.Text = "0";
        //    txt_tamung.Text = "0";
        //    txt_conlai.Text = "0";
        //    txt_tienthue.Text = "0";
        //    txt_mucthue.Text = "0";
        //    txt_bangchu.Text = "Không";            
        //    vitri = 0;
        //    tongtien = 0;
        //    //xoa trang gv
        //}

        private void bt_xemin_Click(object sender, EventArgs e)
        {
            //In hoa don
            try
            {
                DataSet ds = new DataSet();
                string makhdh = "";
                ds.ReadXml(new StringReader(xuly.selectqueryByText("select top 1 MaKHDH from PhieuKHDatHang order by MaKHDH desc")));
                if (ds.Tables.Count > 0)
                {
                    makhdh = ds.Tables[0].Rows[0][0].ToString();
                    Report.frm_In_PhieuKHDatHang khdh = new Report.frm_In_PhieuKHDatHang();
                    khdh.MaKHDH = makhdh;
                    khdh.ShowDialog();
                }

                //Xoa tat cac thong tin sau khi da Luu hoa don va In phieu
                gv_ddh.Rows.Clear();
                txt_tongtien.Text = "0";
                txt_thanhtienhd.Text = "0";
                txt_mucthue.Text = "0";
                txt_tamung.Text = "";
                txt_conlai.Text = "0";
                txt_tienthue.Text = "0";
                txt_bangchu.Text = "không đồng chẵn.";
            }
            catch (Exception ex)
            {
            }
        }

        private void gv_ddh_CellValueChanged(object sender, GridViewCellEventArgs e)
        {
            errorProvider1.Clear();
            try
            {
                if (Regex.IsMatch(gv_ddh.CurrentRow.Cells["SoLuong"].Value.ToString().Trim(), @"^[0-9,',']{0,5}$") == false || int.Parse(gv_ddh.CurrentRow.Cells["SoLuong"].Value.ToString()) < 0)
                {
                    lbl_ThongBao.Text = "Số lượng nhập vào phải lớn hơn không (số lượng > 0) và là con số nguyên. Vui lòng nhập lại";
                    errorProvider1.RightToLeft = false;
                    errorProvider1.SetError(lbl_ThongBao, "Xem lại thông tin trên lưới.");
                    return;
                }
                if (Regex.IsMatch(gv_ddh.CurrentRow.Cells["DonGia"].Value.ToString(), @"^[0-9,',']{0,9}$") == false)
                {
                    lbl_ThongBao.Text = "Đơn giá nhập vào là số nguyên không âm. Vui lòng nhập lại";
                    errorProvider1.RightToLeft = false;
                    errorProvider1.SetError(lbl_ThongBao, "Xem lại thông tin trên lưới.");
                    return;
                }
                if (Regex.IsMatch(gv_ddh.CurrentRow.Cells["KhuyenMai"].Value.ToString().Trim(), @"^(\d{1,2})$") == false || int.Parse(gv_ddh.CurrentRow.Cells["KhuyenMai"].Value.ToString()) > 50)
                {
                    lbl_ThongBao.Text = "Số chiết khấu từ 0 - 50 %";
                    errorProvider1.RightToLeft = false;
                    errorProvider1.SetError(lbl_ThongBao, "Xem lại thông tin trên lưới.");
                    return;
                }
                lbl_ThongBao.Text = "Thông báo!";
                errorProvider1.RightToLeft = true;
            }
            catch (Exception ex)
            {
                logger.Error("Error: " + ex.Message);
            }
        }

        private void gv_ddh_CellEndEdit(object sender, GridViewCellEventArgs e)
        {
            try
            {
                double tongtien_sausua = 0;
                double dongia = double.Parse(gv_ddh.CurrentRow.Cells["DonGia"].Value.ToString());
                int soluong = int.Parse(gv_ddh.CurrentRow.Cells["Soluong"].Value.ToString().Trim());
                float khuyenmai = float.Parse(gv_ddh.CurrentRow.Cells["KhuyenMai"].Value.ToString());
                double thanhtien = (soluong * dongia) - ((soluong * dongia) * khuyenmai) / 100;
                gv_ddh.CurrentRow.Cells["ThanhTien"].Value = thanhtien.ToString("#,##0");

                for (int i = 0; i < gv_ddh.Rows.Count; i++)
                {
                    gv_ddh.Rows[i].Cells["SoLuong"].Value = double.Parse(gv_ddh.Rows[i].Cells["SoLuong"].Value.ToString()).ToString("#,##0");
                    gv_ddh.Rows[i].Cells["DonGia"].Value = double.Parse(gv_ddh.Rows[i].Cells["DonGia"].Value.ToString()).ToString("#,##0");
                    tongtien_sausua += double.Parse(gv_ddh.Rows[i].Cells["ThanhTien"].Value.ToString());
                }
                txt_tongtien.Text = tongtien_sausua.ToString("#,##0");
            }
            catch
            {
            }
        }

        private void bt_timkiem_Click(object sender, EventArgs e)
        {
            frmBC_PhieuKHDatHang khdh = new frmBC_PhieuKHDatHang();
            khdh.Show();
        }  
    }
}
